<?php

class LinkModel extends BaseModel {

    public function tableName() {
        return '{{link}}';
    }

    /**
     * Declares the validation rules.
     * The rules state that username and password are required,
     * and password needs to be authenticated.
     */
    public function rules() {
        return array(
            array('link_title', 'required', 'message' => '名称不能为空！'),
           // array('link_img', 'required', 'message' => '图片不能为空！'),
            array('link', 'required', 'message' => '地址不能为空！'),
            array('link_img,type,level,listorder,description,disabled', 'safe'),
        );
    }

    protected function afterSave() {
        parent::afterSave();
        $this->updateCache();
    }

    protected function afterDelete() {
        parent::afterDelete();
        $this->updateCache();
    }

    protected function updateCache() {
        $this->getIndexLinks(false);
        $this->getInsideLinks(false);
    }

    public function getInsideLinks($cache = true) {
        $key = "LinkModel_getInsideLinks";
        if ($cache) {
            Yii::app()->cache->delete($key);
        }
        $return = Yii::app()->cache->get($key);
        if (!$return) {
            $return = $this->findAll('level = :level and disabled=1', array(':level' => 0));
            Yii::app()->cache->set($key, $return);
        }
        return $return;
    }

    public function getIndexLinks($cache = true) {
        $key = "LinkModel_getIndexLinks";
        if (!$cache) {
            Yii::app()->cache->delete($key);
        }
        $return = Yii::app()->cache->get($key);
        if (!$return) {
            $return = $this->findAll('level = :level and disabled=1', array(':level' => 1));
            Yii::app()->cache->set($key, $return);
        }
        return $return;
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

}
